import {
  ReqAddHospitalSet,
  ReqGetHospitalSetById,
  ReqUpdateHospitalSet,
} from "@/api/hospital/hospitalSet";
import { Button, Card, Form, Input, message, Space } from "antd";
import React, { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";

export default function AddOrUpdateHospital() {
  // 创建一个form对象
  let [form] = Form.useForm();
  // 声明一个加载的状态
  let [loading, setLoading] = useState(false);
  // 获取url中的id
  let { id } = useParams();
  // 表单的onFinish事件,提交表单且进行数据验证成功后的回调
  let finish = async () => {
    try {
      // 获取表单数据
      let fields = form.getFieldsValue();
      setLoading(true);
      if (!id) {
        await ReqAddHospitalSet(fields);
        message.success("添加成功");
        form.setFieldsValue({hosname:'',hoscode:'',apiUrl:'',contactsName:'',contactsPhone:''})
      } else {
        await ReqUpdateHospitalSet({ ...fields, id });
        message.success("编辑成功");
      }
      setLoading(false);
    } catch (e) {
      setLoading(false);
      message.error("添加失败");
    }
  };
  let navigate = useNavigate();
  // 返回医院设置
  let goToBack = () => {
    navigate("/syt/hospital/hospitalset");
  };
  useEffect(() => {
    // 在挂载完毕后,得到当前id医院的信息
    let getHospital = async () => {
      let hospital = await ReqGetHospitalSetById(id as string);
      form.setFieldsValue(hospital);
    };
    getHospital();
  }, [id]);
  return (
    <Card>
      <Form
        name="basic"
        labelCol={{ span: 3 }}
        wrapperCol={{ span: 16 }}
        form={form}
        onFinish={finish}
      >
        <Form.Item
          label="医院名称"
          name="hosname"
          rules={[{ required: true, message: "医院名称不能为空" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="医院编号"
          name="hoscode"
          rules={[{ required: true, message: "医院编号不能为空" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="api 基础路径"
          name="apiUrl"
          rules={[{ required: true, message: "api基础路径不能为空" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="联系人姓名"
          name="contactsName"
          rules={[{ required: true, message: "联系人姓名不能为空" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="联系人手机"
          name="contactsPhone"
          rules={[
            { required: true, message: "联系人手机不能为空" },
            { pattern: /^1\d{10}$/, message: "手机号格式错误" },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 3, span: 16 }}>
          <Space>
            <Button type="primary" htmlType="submit" loading={loading}>
              保存
            </Button>
            <Button onClick={goToBack}>返回</Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  );
}
